# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         mock.py
# Description:  根据请示的url提供相应的mock
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2020/9/30 11:34
# -------------------------------------------------------------------------------
import json
import logging

import jsonpath
from django.http import HttpResponse
from apps.MockService.models import UrlMock
from apps.MockService.views.common import CommonMockAPIView

logger = logging.getLogger()

__all__ = ['UrlMockAPIView']


class UrlMockAPIView(CommonMockAPIView):

    def get(self, request, *args, **kwargs):
        """
        http get 请求
        """
        request_path = request.path
        url = request_path.split('/mock/')[-1]
        method = request.method.upper()
        query_params = request.query_params
        data = request.data
        logger.info('URLMock：查询参数：{}'.format(json.dumps(query_params, ensure_ascii=False)))
        logger.info('URLMock：消息体参数：{}'.format(json.dumps(data, ensure_ascii=False)))

        url_mock = UrlMock.objects.filter(url__in=(url, '/' + url), method=method, is_deleted=False).first()
        if not url_mock:
            return HttpResponse(
                content='URLMock：未定义Mock服务，接口请求url：{url}，http请求方法：{method}'.format(url=url, method=method),
                content_type='application/json', charset='utf-8')

        if url_mock.is_check and url_mock.check_params:
            # 必填参数校验
            check_params = url_mock.check_params.split(',')
            nonpass_params = []
            for item in check_params:
                expr = '$.{}'.format(item)
                if not (jsonpath.jsonpath(query_params, expr) or jsonpath.jsonpath(data, expr)):
                    nonpass_params.append(item)
            if nonpass_params:
                return HttpResponse(content='URLMock：{}参数不能为空'.format(nonpass_params), content_type='application/json',
                                    charset='utf-8')
        result = url_mock.mock_data or '{}'
        http_response = HttpResponse(content=result, content_type='application/json',
                                     charset='utf-8')
        status_code = url_mock.status_code
        if status_code is not None:
            http_response = HttpResponse(status=status_code, content=result, content_type='application/json',
                                         charset='utf-8')
        return http_response
